package main.java.零钱通.dao;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * @Auther:Liu
 * @Testname:moneybase
 * @Date:2025/3/21 11:29
 */
public class moneybase {
    private static final ThreadLocal<Connection> THREAD_LOCAL = new ThreadLocal<>();
    private static DruidDataSource ds;

    //加载驱动
    static {

        try {
            Properties properties = new Properties();
            InputStream res = moneybase.class.getClassLoader().getResourceAsStream("database.properties");
            properties.load(res);
            ds = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //获取链接
    public static Connection getConnection() throws Exception {
        Connection connection = THREAD_LOCAL.get();
        if (connection == null) {
            connection = ds.getConnection();
            THREAD_LOCAL.set(connection);
        }
        return connection;
    }

    //关闭资源
    public static void close(Connection connection, Statement statement, ResultSet resultSet) {
        try {
            if (resultSet != null) {
                resultSet.close();
            }
            if (statement != null) {
                statement.close();
            }
            if (connection != null) {
                connection.close();
                THREAD_LOCAL.remove();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
